package com.wuwei.elearning.question.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.question.domain.Collect;
import com.wuwei.elearning.question.mapper.CollectMapper;
import com.wuwei.elearning.question.service.CollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuwei
 * @since 2024-03-28
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    @Resource
    private CollectMapper collectMapper;

    /**
     * 先去查询数据库中有无该记录，如果有则进行修改，如果无则新增
     用户点击收藏或取消收藏，则会添加
     */
//    @Transactional
    @Override
    public void updateCollect(Long account, Integer collectFlag,  Long questionId) {

        //如果collectFlag为1表示是添加收藏，则往数据库增加一条数据
        if (collectFlag==1) {
            Collect collect1 = new Collect();
            collect1.setCreatedTime(LocalDateTime.now());
            collect1.setUserAccount(account);
            collect1.setQuestionId(questionId);
            int insert = collectMapper.insert(collect1);
            if (insert!=1) {
                throw new ElearningMysqlException(30001,"收藏失败！");
            }
        } else {//否则表示是取消收藏，则往数据库中删除一条数据
            LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Collect::getUserAccount,account).eq(Collect::getQuestionId,questionId);
            int delete = collectMapper.delete(queryWrapper);
            if (delete!=1) {
                throw new ElearningMysqlException(30001,"取消收藏失败！");
            }
        }
    }
}
